package com.shareyi.wox.core.interceptor;

import java.net.HttpURLConnection;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.shareyi.wox.context.ServletActionContext;
import com.shareyi.wox.core.ActionInvocation;
import com.shareyi.simpleserver.core.HttpRequest;


public class LocalVisitInterceptor implements Interceptor {

	public void destroy() {

	}

	public void init(Map<String, String> configParams) {
		

	}

	public String intercept(ActionInvocation invocation) throws Exception {
		HttpRequest request=ServletActionContext.getRequest();
		String remoteAddr=request.getRemoteAddr();
		String referer=request.getRequestHeader("Referer");
		referer=referer==null?request.getRequestHeader("referer"):referer;
		referer=referer==null?request.getRequestHeader("REFERER"):referer;
		
		if(!remoteAddr.equals("127.0.0.1")&&!remoteAddr.equals("localhost"))
		  {
			//不允许访问
			ServletActionContext.getResponse().setStatusCode(HttpURLConnection.HTTP_NOT_AUTHORITATIVE);
			return null;
		  }else if(StringUtils.isEmpty(referer)||referer.startsWith("http://localhost")||referer.startsWith("http://127.0.0.1")){
			  return  invocation.invoke();
		  }else{
				//不允许访问
				ServletActionContext.getResponse().setStatusCode(HttpURLConnection.HTTP_NOT_AUTHORITATIVE);
				return null;
		  }
	}

}
